/**
 * 图书馆管理系统主JavaScript文件
 */
document.addEventListener('DOMContentLoaded', function() {
    // 初始化工具提示
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
    
    // 自动关闭警告消息
    setTimeout(function() {
        var alerts = document.querySelectorAll('.alert-dismissible');
        alerts.forEach(function(alert) {
            var bsAlert = new bootstrap.Alert(alert);
            bsAlert.close();
        });
    }, 5000);
    
    // 密码确认验证
    var password = document.getElementById('password');
    var confirmPassword = document.getElementById('confirmPassword');
    
    if (password && confirmPassword) {
        function validatePassword() {
            if (password.value != confirmPassword.value) {
                confirmPassword.setCustomValidity('密码不匹配');
            } else {
                confirmPassword.setCustomValidity('');
            }
        }
        
        password.addEventListener('change', validatePassword);
        confirmPassword.addEventListener('keyup', validatePassword);
    }
    
    // 图书搜索表单增强
    var searchForm = document.querySelector('form[action="/books/search"]');
    if (searchForm) {
        searchForm.addEventListener('submit', function(e) {
            var keyword = searchForm.querySelector('input[name="keyword"]').value;
            if (keyword.trim() === '') {
                e.preventDefault();
                alert('请输入搜索关键词');
            }
        });
    }
    
    // 借阅表单确认
    var borrowForms = document.querySelectorAll('form[action="/loans/borrow"]');
    borrowForms.forEach(function(form) {
        form.addEventListener('submit', function(e) {
            if (!confirm('确定要借阅这本书吗？')) {
                e.preventDefault();
            }
        });
    });
    
    // 归还操作已使用Bootstrap模态框处理，无需额外JavaScript确认
    
    // 图书数量验证
    var quantityInput = document.getElementById('quantity');
    var availableQuantityInput = document.getElementById('availableQuantity');
    
    if (quantityInput && availableQuantityInput) {
        quantityInput.addEventListener('change', function() {
            availableQuantityInput.max = this.value;
            if (parseInt(availableQuantityInput.value) > parseInt(this.value)) {
                availableQuantityInput.value = this.value;
            }
        });
    }
    
    // 高亮当前导航项
    highlightCurrentNavItem();
});

/**
 * 高亮当前导航项
 */
function highlightCurrentNavItem() {
    var currentPath = window.location.pathname;
    var navLinks = document.querySelectorAll('.navbar-nav .nav-link');
    
    navLinks.forEach(function(link) {
        var href = link.getAttribute('href');
        if (href === currentPath || 
            (href !== '/' && currentPath.startsWith(href))) {
            link.classList.add('active');
        }
    });
}

/**
 * 确认删除操作
 * @param {string} message - 确认消息
 * @returns {boolean} - 是否确认
 */
function confirmDelete(message) {
    return confirm(message || '确定要删除吗？此操作不可撤销。');
}

/**
 * 格式化日期
 * @param {Date} date - 日期对象
 * @returns {string} - 格式化的日期字符串
 */
function formatDate(date) {
    if (!date) return '';
    var d = new Date(date);
    var year = d.getFullYear();
    var month = ('0' + (d.getMonth() + 1)).slice(-2);
    var day = ('0' + d.getDate()).slice(-2);
    return year + '-' + month + '-' + day;
}

/**
 * 计算剩余天数
 * @param {string} dueDate - 到期日期字符串
 * @returns {number} - 剩余天数
 */
function calculateRemainingDays(dueDate) {
    var due = new Date(dueDate);
    var today = new Date();
    var timeDiff = due.getTime() - today.getTime();
    return Math.ceil(timeDiff / (1000 * 3600 * 24));
}

/**
 * 显示或隐藏加载指示器
 * @param {boolean} show - 是否显示
 */
function toggleLoadingIndicator(show) {
    var indicator = document.getElementById('loadingIndicator');
    if (!indicator) return;
    
    if (show) {
        indicator.classList.remove('d-none');
    } else {
        indicator.classList.add('d-none');
    }
}
